package com.inossem.warehousestorage_inossem.utils;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.widget.EditText;

import com.inossem.utils.constant.QRCodeConstant;
import com.inossem.utils.log.LogUtils;

/**
 * Created by leij on 2017/7/20.
 */

public abstract class QRCodeEditTextWatcher implements TextWatcher {

    private EditText mEditText;

    private String mBeforeText;

    private boolean mRetainText = false;

    public QRCodeEditTextWatcher(EditText editText) {
        mEditText = editText;
    }

    public QRCodeEditTextWatcher(EditText editText, boolean retainText) {
        mEditText = editText;
        mRetainText = retainText;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        String beforeText = TextUtils.isEmpty(s) ? "" : s.toString();
        mBeforeText = beforeText;
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        String textChanged = TextUtils.isEmpty(s) ? "" : s.toString();
        if (textChanged.endsWith(QRCodeConstant.QRCODE_SECURITY)) {
            int length = QRCodeConstant.QRCODE_SECURITY.length();
            String result = textChanged.substring(0, textChanged.length() - length);
            result = result.substring(mBeforeText.length());
            if (mEditText != null) {
                LogUtils.i("mRetainText:" + mRetainText);
                if (mRetainText) {
                    mEditText.setText(result);
                } else {
                    mEditText.setText("");
                }
            }
            onScan(result);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {
//        String text = s.toString();
//        LogUtils.i("text:" + text);
//        if (text.endsWith(Constant.QR_CODE_SECURITY)) {
//            int length = Constant.QR_CODE_SECURITY.length();
//            String result = text.substring(0, text.length() - length);
//            LogUtils.i("result:" + result);
//            if (mEditText != null) {
//                mEditText.setText(result);
//            }
//            onScan(result);
//        }
    }

    public abstract void onScan(String text);
}
